package com.ycm.serializers;

import cn.hutool.core.util.StrUtil;
import com.fasterxml.jackson.core.JacksonException;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonNode;
import com.ycm.enums.BaseEnum;
import org.springframework.beans.BeanUtils;

import java.io.IOException;

/**
 * 自定义枚举反序列化器
 *
 * @author ycm
 * @date 2024-07-12
 */
public class CustomEnumDeserializer extends JsonDeserializer<BaseEnum> {
    @Override
    public BaseEnum deserialize(JsonParser jsonParser, DeserializationContext context) throws IOException, JacksonException {
        JsonNode enumValue = jsonParser.getCodec().readTree(jsonParser);
        //前端值的枚举值为空时，返回null
        if (enumValue == null || StrUtil.isBlank(enumValue.asText())) {
            return null;
        }

        Class clazz = BeanUtils.findPropertyType(jsonParser.getCurrentName(), jsonParser.getCurrentValue().getClass());
        BaseEnum instance = BaseEnum.getInstance(clazz, enumValue.asInt());
        if (instance == null) {
            //若前端传了枚举值，但与对应的枚举类不匹配，抛出异常
            throw new RuntimeException(String.format("枚举[%s]无法识别的值：%s", clazz.getName(), enumValue.asInt()));
        }

        return instance;
    }
}
